<template>
  <div style="height: calc(100% - 50px)">
    <q-table
      :card-container-style="{ overflow: 'auto' }"
      card-container-class="q-pl-sm q-pr-sm q-pb-sm"
      class="no-border-radius full-height"
      grid
      :rows="normalAmr"
      row-key="device"
      :filter="filter"
      :pagination="{ rowsPerPage: 0 }"
      hide-header
    >
      <template v-slot:top-left>
        <q-btn
          label="刷新列表"
          icon="replay"
          color="primary"
          @click="getNormalAmr"
        />
      </template>
      <template v-slot:top-right>
        <!--      <amr-detail-dialog ref="statusDialog"/>-->
        <div class="row q-gutter-x-sm items-center">
          <q-input
            v-if="$q.screen.gt.xs"
            outlined
            dense
            debounce="300"
            clearable
            v-model="filter"
            placeholder="搜索设备"
            :dark="ui.isDark"
          >
            <template v-slot:prepend>
              <q-icon name="search" />
            </template>
          </q-input>
          <!--        <q-btn label="全部关机" icon="power_settings_new" color="negative" @click="shutdownAll"/>-->
        </div>
      </template>
      <template v-slot:item="props">
        <div class="q-pa-sm col-xs-12 col-sm-6 col-md-4 col-lg-3">
          <q-card>
            <q-card-section class="row items-center">
              <div
                class="text-h6 text-bold text-black no-wrap overflow-hidden"
                style="max-width: 80%; height: 2rem"
              >
                {{ props.row.device }}
              </div>
              <q-space />
              <div class="text-right">
                <!--              <div class="text-grey-7">{{props.row.version}}</div>-->
                <!--              <div class="text-grey-7">{{props.row.packageName}}</div>-->
                <q-btn
                  label="连接"
                  @click="setRobotIP(props.row.network.IPv4)"
                  :class="ui.btnClass"
                  v-if="props.row.network !== null"
                />
                <div class="text-grey-7" v-else>Controller未配置</div>
              </div>
            </q-card-section>
            <q-separator />
            <q-list dense @click="statusDialog.show(props.row.device)">
              <q-item clickable v-ripple>
                <q-item-section side class="text-subtitle2"
                  >设备类型</q-item-section
                >
                <q-item-section class="text-right">{{
                  amrTypes[props.row.type] || props.row.type
                }}</q-item-section>
              </q-item>
              <q-item
                dense
                v-for="item in robotState"
                v-bind:key="item.key"
                clickable
                v-ripple
              >
                <q-item-section side>{{ item.title }}</q-item-section>
                <q-item-section class="text-right">{{
                  props.row[item.key] || "没有数据"
                }}</q-item-section>
              </q-item>
              <q-item
                clickable
                v-ripple
                :class="
                  props.row.batteryStatus === null
                    ? 'text-positive'
                    : 'text-negative'
                "
              >
                <q-item-section class="text-subtitle2">电池状态</q-item-section>
                <q-item-section class="text-right">
                  <template v-if="props.row.charge">充电中</template>
                  {{
                    batteryStatus[props.row.batteryStatus] ||
                    props.row.batteryStatus
                  }}
                </q-item-section>
              </q-item>
              <q-item
                clickable
                v-ripple
                :class="
                  ['idle', 'running'].includes(props.row.status) &&
                  !props.row.emergencyStop &&
                  props.row.state !== 'MANUAL'
                    ? 'text-positive'
                    : 'text-negative'
                "
              >
                <q-item-section class="text-subtitle2">运动状态</q-item-section>
                <q-item-section
                  class="text-right"
                  v-if="props.row.emergencyStop"
                  >急停</q-item-section
                >
                <q-item-section
                  class="text-right"
                  v-else-if="props.row.state === 'MANUAL'"
                  >手动模式</q-item-section
                >
                <q-item-section class="text-right" v-else>{{
                  props.row.status || "没有状态信息"
                }}</q-item-section>
              </q-item>
              <q-item
                :class="
                  props.row.centerConnected ? 'text-positive' : 'text-negative'
                "
                clickable
                v-ripple
              >
                <q-item-section
                  >{{
                    props.row.centerConnected ? "" : "已掉线"
                  }}
                  上次更新</q-item-section
                >
                <q-item-section class="text-right">{{
                  props.row.updateTime
                }}</q-item-section>
              </q-item>
            </q-list>
            <q-list dense>
              <q-item>
                <q-item-section>更新</q-item-section>
                <q-item-section class="text-right"
                  ><q-btn
                    flat
                    round
                    style="width: 40px"
                    class="absolute-right q-mr-md"
                    icon="arrow_upward"
                    @click="update(props.row.device)"
                /></q-item-section>
              </q-item>
            </q-list>
            <q-list dense>
              <!--            <map-info :map-id="props.row.mapID" />-->
              <q-item
                v-if="props.row.network !== null"
                clickable
                v-ripple
                @click="setRobotIP(props.row.network.IPv4)"
              >
                <q-item-section side>设备IP</q-item-section>
                <q-item-section class="text-right">{{
                  props.row.network.IPv4
                }}</q-item-section>
              </q-item>
              <q-item v-else v-ripple>
                <q-item-section class="text-warning text-center text-bold"
                  >没有正确配置Linux-Controller</q-item-section
                >
              </q-item>
            </q-list>
          </q-card>
        </div>
      </template>
    </q-table>
    <q-inner-loading :showing="loading">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { api } from "boot/axios.js";
// import AmrDetailDialog from 'components/status/amrDetail/index.vue'
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import { useAPIStore } from "stores/api";
import { useUiStore } from "stores/ui";
import { useFunctionsStore } from "stores/functions";
import deviceWs, { isConnected, closeWs } from "src/utils/deviceWs";
import { closeCenterWs } from "components/rosMapRemote/centerWs.js";
// import MapInfo from 'components/status/MapInfo.vue'

const robotState = [
  {
    title: "设备型号",
    key: "model",
  },
  {
    title: "电池电量",
    key: "batteryNumber",
  },
  {
    title: "电池电压",
    key: "batteryVolt",
  },
];

const batteryStatus = {
  null: "正常",
  low: "低于预警电量",
  limit: "低于极限电量",
};

// 监听机器人连接
watch(isConnected, (value) => {
  // 成功连接切换模式切换页面弹窗取消
  if (value) {
    // 关闭中控连接
    closeCenterWs();
    useFunctionsStore().mode = "remote";
    $router.push("/main");
    loading.value = false;
    useFunctionsStore().setRoutes();
  }
});

const ui = useUiStore();
const $q = useQuasar();
const normalAmr = ref([]);
const $router = useRouter();
const filter = ref("");
const loading = ref(false);
onMounted(() => {
  getNormalAmr();
});

function getNormalAmr() {
  api.get(useAPIStore().centerUrl + "center/status").then((rs) => {
    normalAmr.value = rs.data;
  });
}

const amrTypes = {};

function setRobotIP(data) {
  console.log(data);
  $q.dialog({
    title: "切换至该设备",
    message: "是否要切换当前控制的机器人至IP为 " + data + " 的设备？",
    ok: { label: "确定", class: "text-bold", flat: true },
    cancel: {
      label: "取消",
      class: "text-bold",
      color: "secondary",
      flat: true,
    },
    persistent: true,
  }).onOk(() => {
    // 切换地址
    useAPIStore().deviceIP = data;
    useAPIStore().rosIP = data;
    // 机器人连接
    deviceWs();
    // 弹窗显示
    loading.value = true;
    // 3秒延时判断
    setTimeout(() => {
      // 3秒后自动关闭
      loading.value = false;
      // 判断机器人是否连接成功
      if (!isConnected.value) {
        // 失败弹窗提示
        $q.notify({
          type: "warning",
          message: "连接失败请重试",
          position: "bottom",
        });
        // 断开机器人连接
        closeWs();
      }
    }, 3000);
  });
}
function update(device) {
  $q.dialog({
    title: "更新服务",
    message: "是否立即更新" + device + "机器人？",
    ok: { label: "确定", class: "text-bold", flat: true },
    cancel: {
      label: "取消",
      class: "text-bold",
      color: "secondary",
      flat: true,
    },
    persistent: true,
  }).onOk(() => {
    api
      .get(useAPIStore().centerUrl + "center/send", {
        params: { device, type: "update" },
      })
      .then((rs) => {
        if (rs.data === "done") {
          $q.notify({
            type: "positive",
            message: "更新指令已下发",
            position: "bottom",
          });
        } else {
          $q.notify({ type: "warning", message: rs.data, position: "bottom" });
        }
      });
  });
}
</script>
